#!/bin/bash
# Copyright 2024 Hangzhou Yingyi Technology Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

function pre_pack() {
  if ! command -v dtc &>/dev/null; then
    echo "Error: dtc command not found. Please install dtc." >&2
    exit 1
  fi

  dtc -I dts -O dtb -o $BOARD_PACK_BUILD_PATH/rk3568.dtb $BOARD_PATH/dts/rk3568.dts 2>/dev/null
  if [ $? != 0 ]; then
    echo "Error: generating dtb file failed."
    exit 1
  fi

  chmod u+x $BOARD_PATH/third_party/tools/resource_tool
  $BOARD_PATH/third_party/tools/resource_tool $BOARD_PACK_BUILD_PATH/rk3568.dtb 2>/dev/null
  if [ $? != 0 ]; then
    echo "Error: generating resource.img file failed."
    exit 1
  fi
  mv $PWD/resource.img $BOARD_PACK_BUILD_PATH/resource.img

  src_its_file=$BOARD_PATH/third_party/boot.its
  target_its_file=$BOARD_PACK_BUILD_PATH/.tmp_its
  kernel_dtb_file=$BOARD_PACK_BUILD_PATH/rk3568.dtb
  resource_file=$BOARD_PACK_BUILD_PATH/resource.img
  kernel_image=$KERNEL_BUILD_PATH/kernel.img
  pack_img_file=$BOARD_PACK_BUILD_PATH/boot.img

  cp $src_its_file $target_its_file

  sed -i "s/{{DTB}}/${kernel_dtb_file//\//\\/}/g" $target_its_file
  sed -i "s/{{KERNEL_IMG}}/${kernel_image//\//\\/}/g" $target_its_file
  sed -i "s/{{RESOURCE_IMG}}/${resource_file//\//\\/}/g" $target_its_file

  chmod u+x $BOARD_PATH/third_party/tools/mkimage
  $BOARD_PATH/third_party/tools/mkimage -f $target_its_file -E -p 0x800 $pack_img_file >/dev/null 2>&1
  if [ $? != 0 ]; then
    echo "Error: generating boot.img file failed."
    exit 1
  fi

  rm -f $resource_file $kernel_dtb_file $target_its_file

  cp $BOARD_PATH/README.md $BOARD_PACK_BUILD_PATH/BOARD_README.md
  cp $KERNEL_PATH/README.md $BOARD_PACK_BUILD_PATH/KERNEL_README.md
  cp $BOARD_PATH/bootloaders/uboot.img $BOARD_PACK_BUILD_PATH/uboot.img

  IMAGE_NAME=kernel.img
}
